package leetcode.f1t100;

/**
 * 给定一个非降序有序数组, 使用O(n)时间O(1)空间, 实现删除元素, 使得数组元素相同值出现次数最多两次
 * https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
 *
 * @author lichx
 * @createTime 2024/1/29 11:49
 */
public class Q80_RemoveDuplicatesFromSortedArrayII {

    public int removeDuplicates(int[] nums) {
        if(nums.length<=2){
            return nums.length;
        }
        int cur = nums[0], times = 1, k = 1;
        for (int i = 1; i < nums.length; i++) {
            if(nums[i] == cur) {
                times++;
                if(times<=2){
                    nums[k] =cur;
                    k++;
                }
            }else {
                times=1;
                cur = nums[i];
                nums[k] =cur;
                k++;
            }
        }
        return k;
    }

    public static void main(String[] args) {
        Q80_RemoveDuplicatesFromSortedArrayII bean = new Q80_RemoveDuplicatesFromSortedArrayII();
        int[] nums = {1,1,1,2,2,2,3,3,3};
        System.out.println(bean.removeDuplicates(nums));
        for (int num : nums) {
            System.out.println(num);
        }
    }
}
